<?php
/**
 * Date: 15-1-22
 * Time: 上午10:49
 * @package  ajax
 * @subpackage  dunch
 * @author   allen.qiang <allen.qiang@fistforward.com>
 */

quanli_require('module/base/customer/quanliCust.class.php');//载入会员类
quanli_require('module/base/dunch/dunch.class.php');//载入下午茶操作类
//加载短信类
quanli_include('module/base/common/quanliSms.class.php');
class ajax_dunchTreat {

    public function execute() {

        if (isset($_REQUEST['operFlg']) && is_numeric($_REQUEST['operFlg']) && $_REQUEST['operFlg'] > 0) {

            switch ($_REQUEST['operFlg']) {

                case 1://验证会员信息
                    $this->checkCustMaster();
                    break;
                case 2://发送短信验证码
                    $this->send_sms();
                    break;
                case 3://立即体验
                    $this->checkCode();
                    break;
                case 4://支付宝支付刷新页面
                    $this->ckeackPay();
                    break;
                case 5://保存用户访问记录
                    $this->savein();
                    break;
                case 6://验证登录状态
                    $this->checkLogin();
                    break;

                case 7://获取所有套餐总库存
                    $this->packageNum();
                    break;

                case 8://存入session 请客数量 免单数量 日期
                    $this->numInfo();
                    break;

                case 9://提交订单
                    $this->createBill();
                    break;
                case 10://获取配送时间
                    $this->sendDate();
                    break;
                case 11://领取记录
                    $this->addDunchReceive();
                    break;
                case 12://选择套餐页面
                    $this->checkSelect();
                    break;

                case 13://申请权益
                    $this->treatApply();
                    break;

                case 14://摇奖
                    $this->ernie();
                    break;

                default:
                    $this->toReturn('参数错误');
                    break;

            }

        } else {
            $this->toReturn('参数错误');
        }


    }

    /**
     * 返回信息
     * @param string $message
     * @param int $code
     * @param mixed $data
     */
    private function toReturn( $message, $code = 400, $data = '' ) {

        die( json_encode( array( 'code' => $code, 'message' => $message, 'data' => $data ) ) );

    }


    /*
     * 验证登录状态
     */
    public function checkLogin(){
        global $G_SHOP;
        //$pageVal=$_COOKIE['pageVal'];
        $num=$_REQUEST['num'];
        $custID=$G_SHOP->currentCustomerID;
        $treatSql="select count(1) as treatNum from dunch_cust_master where custID=? and  is_treat=1";
        $treatInfo=$G_SHOP->DBCA->stmt_query($treatSql,'s',$custID);
        setcookie('buynum_cookie', $num, time()+3600*24*7,'/','fistforward.com');//保存用户行为
        if($custID && $treatInfo[0]->treatNum){
            returnJsonData('YES',200);
        }else{

            returnJsonData('会员信息错误',400);
        }


    }

    /**
     * 验证会员信息
     */
    public  function checkCustMaster(){

        global $G_SHOP;
        $phone=$_REQUEST['phone'];
        $checkSql="select custID,pcustID from dunch_cust_master where custID=?  and  brandID=1 and  is_treat=1";
        $quest=$G_SHOP->DBCA->stmt_query($checkSql,'s',$phone);
        if(!empty($quest)){

            foreach($quest as $quest1){
                $questArray=array(
                    'custID'=>$quest1->custID,
                    'pcustID'=>$quest1->pcustID
                );
            }

        }
        if($questArray['pcustID']){

            returnJsonData('ok',200,$questArray);
        }else{
            returnJsonData('ok',400);
        }

        // returnJsonData('ok',200,$first_level_array);

    }
    /*
     * 发送短信验证码
     */
    public function send_sms(){
        global $G_SHOP;
        $phone=$_REQUEST['phone'];//手机号码
        //加载短信类
        quanli_include('module/base/common/quanliSms.class.php');

        //实例化短信类
        $quanliSms = new quanliSms();


        if (!isset($phone) || !is_mobile($phone)) {
            returnJsonData('参数错误');
        }


        $current_time = time(); //当前时间戳
        $last_send_time = $G_SHOP->sessionCache_get('sms_yzm_time_' . $phone); //上一次发放短信的时间戳
        if (!empty($last_send_time) && $current_time - $last_send_time < 30) {
            returnJsonData('手机短信已发送，请30s以后再试');
        }

        /**
         * ============================
         * 发送短信
         * ============================
         */

        //生成短信验证码
        $sms_yzm = $quanliSms->createSmsCode();

        //生成短信内容
        $data_array = array(
            '$sms_yzm' => $sms_yzm,
            '$mobile' => $phone
        );
        $sms_content = $quanliSms->getSmsContent( 'dunch_mobile', $data_array );
        if (!$sms_content) {
            returnJsonData('短信初始化失败', 404);
        }

        //发送短信
        $result_array = $quanliSms->sendSMS( $phone, $sms_content );

        /**
         * ============================
         * 发送短信
         * ============================
         */
        // if ($result_array['code'] == 200) { //本地环境 注释掉
        //保存短信验证码到redis
        $G_SHOP->sessionCache_set('sms_yzm_' . $phone, md5($sms_yzm), 3600);//将验证码信息保存到memcache中去
        $G_SHOP->sessionCache_set('sms_yzm_time_' . $phone, time(), 3600);

        //    }
        returnJsonData($result_array,200);
    }
    /*
     * 立即体验
     * 验证手机号and短信验证码是否匹配
     */
    public function checkCode(){

        global $G_SHOP;
        $phone=$_REQUEST['phone'];
        $code=$_REQUEST['code'];
        $page=$_REQUEST['page'];

    //假如page为空 且非下午茶会员 非具有请客权益 则没有来源页。跳申请权益页面start
    $dunchCustSql="SELECT count(1) as tnum  FROM  dunch_cust_master  WHERE  custID=? and is_treat=1";
    $dunchCustInfo=$G_SHOP->DBCA->stmt_query($dunchCustSql,'s',$phone);

    if($dunchCustInfo[0]->tnum==0 && $page=='' ){
        returnJsonData('非下午茶我要请客权益会员',500);
        //假如page为空 且非下午茶会员 非具有请客权益 则没有来源页。跳申请权益页面end
    }else if($dunchCustInfo[0]->tnum || $page=='select' ){
      //检查短信验证码
        $sms_ysm = $G_SHOP->sessionCache_get('sms_yzm_' . $phone);
        if (is_null($sms_ysm)) {
            returnJsonData('短信验证码已失效', 400);
        } elseif ($sms_ysm != md5($code)) {
            returnJsonData('短信验证码有误',400);
        }


        $G_SHOP->sessionCache_remove( 'sms_yzm_' .$phone );
        $G_SHOP->sessionCache_remove( 'sms_yzm__time_' . $phone );
        //$zc=$this->quickLogin();
        //实例会员类
        $quanliCust = new quanliCust();

        //查询会员信息
        $arg_array = array(
            'custID' =>$phone
        );

        $customer_array = $quanliCust->searchCustomerDetail( $arg_array );


            // 选择套餐页面
            if($page=='select'){
                setcookie('dunchCookie_select', $phone, time()+3600*24*7,'/','fistforward.com');//手机号存入cookie
            }
            setcookie('dunchCookie_custID', $customer_array['custID'], time()+3600*24*7,'/','fistforward.com');//手机号存入cookie
            setcookie('dunchCookie_pcustID', $customer_array['pcustID'], time()+3600*24*7,'/','fistforward.com');//会员ID存入cookie
            if($dunchCustInfo[0]->tnum){
                //更新会员登录信息
                $quanliCust->shopCheckin( $customer_array, 0 );
            }
            returnJsonData('短信验证成功',200);
        }
        else{
            returnJsonData('会员信息错误',500);
        }

    }


    public function ckeackPay(){
        global $G_SHOP;
        //$sta=1;未支付
        //$sta=2;支付成功
        //$sta=3;订单取消
        $_REQUEST['bill_no'];
        $bill_no= $_REQUEST['bill_no'];
        $selSql="SELECT bill_status FROM  bill_master where  bill_no=$bill_no";
        $query=$G_SHOP->DBCA->stmt_query($selSql);
        $query[0]->bill_status;
        if($query[0]->bill_status==0){
            returnJsonData('未支付',400);
        }elseif($query[0]->bill_status==1){
            returnJsonData('支付成功',200);
        }
    }
    public function savein(){
        global $G_SHOP;

        setcookie('savein_cookie', 1, time()+3600*24*30,'/','fistforward.com');//保存用户行为

        returnJsonData(1 ,200);
    }
    //查询当日库存总量
    public function packageNum(){
        global $G_SHOP;

        if($G_SHOP->currentCustomerID){
            $treatSql="select count(1) as dunchNum from  dunch_cust_master where  custID=? and is_treat=1";
            $treatInfo=$G_SHOP->DBCA->stmt_query($treatSql,'s',$G_SHOP->currentCustomerID);
            if($treatInfo[0]->dunchNum==0){
                returnJsonData('请登录',404);
            }
        }else{
            returnJsonData('请登录',404);
        }


        $tdate=$_REQUEST['tdate'];//套餐销售日期
        $buyNum=$_REQUEST['buyNum'];//购买套餐数量
        $sumSql="SELECT SUM(package_num) as sumPackage FROM  dunch_sale WHERE sale_date =? ";
        $numArray=$G_SHOP->DBCA->stmt_query($sumSql,'s',$tdate);
        if($numArray[0]->sumPackage>$buyNum || $numArray[0]->sumPackage==$buyNum){
            returnJsonData('库存充足',200);
        }else{
            returnJsonData($numArray[0]->sumPackage,400);
        }

    }
    // 存入session信息
    public function numInfo(){
        global $G_SHOP;
        $buyNum=$_REQUEST['buyNum'];//请客数量
        $tdate=$_REQUEST['tdate'];//套餐销售日期
       $goodsInfo=$G_SHOP->sessionCache_get("numIfo");

        if( empty($goodsInfo) || $goodsInfo['buyNum']!=$buyNum){
            if(isset($buyNum)&&!empty($buyNum) && $buyNum>1 && $buyNum <11){
                $numIfo=array(
                    'mnum'=>0,
                    'buyNum'=>$buyNum,
                    'tdate'=>$tdate
                );

            }else{
                $numIfo=array(
                    'mnum'=>0,
                    'buyNum'=>2,
                    'tdate'=>$tdate
                );
            }
            $G_SHOP->sessionCache_set("numIfo",$numIfo,G_LOGINSESSION_TIMEOUT);

        }


        returnJsonData('成功存入session',200);
    }
    //提交订单（创建订单）
    public function createBill(){
        global $G_SHOP;
        $tdate=$_REQUEST['tdate'];//配送日期
        $buyNum=$_REQUEST['buyNum'];//购买数量
        $pdate=$_REQUEST['pdate'];//配送时间
        $username=$_REQUEST['username'];//收货人姓名
        $tel=$_REQUEST['tel'];//收货人手机
        $address=$_REQUEST['address'];//收货地址
        $payID=$_REQUEST['payID'];//支付方式ID
        $teamark=$_REQUEST['teamark'];//请客理由
        $numIfo=$G_SHOP->sessionCache_get("numIfo");//获取session内数据
        $fdate=explode(" ",$pdate);
        $strtime=explode("~",$fdate[1]);
        $startTime=$strtime[0].":00";
        $endTime=$strtime[1].":00";
        $stockSql='select sum(package_num) as package_num from dunch_sale where sale_date=?';
        $drawInfo=$G_SHOP->DBCA->stmt_query($stockSql,'s',$tdate);
        if($drawInfo[0]->package_num<$buyNum){
            returnJsonData($drawInfo[0]->package_num,300);
        }
        $G_SHOP->currentCustomerID;//会员手机号
        if($numIfo['buyNum']==''){
            returnJsonData('请重新下单', 400);
        }



        //套餐销售日期 ！=选择的配送日期
        if($numIfo['tdate'] != $tdate){
            returnJsonData('哎呀,<br/>已超过本日最晚下单时间，<br/>您可以返回选购明天的套餐1！',400);
        }
        $nowDateTime=date('Y-m-d H:i:s');

        $tdate2=$tdate." 16:00:01";

        //下单时间  》配送日期内的时间
        if($nowDateTime>$tdate2){
            returnJsonData("哎呀,<br/>已超过本日最晚下单时间，<br/>您可以返回选购明天的套餐2",400);
        }
        //下单时间+25分钟-7分钟 取最近的0 - 15 - 30 - 45 - 0 start

        $start= time()+1500;
        $zeroMin=strtotime(date('Y-m-d H',$start).'00');  //当前小时内四个时间段 00  15  30  45
        $fifMin=strtotime(date('Y-m-d H',$start).'15');
        $thirtyMin=strtotime(date('Y-m-d H',$start).'30');
        $f_fiveMin=strtotime(date('Y-m-d H',$start).'45');
        //判断开始时间在四个时间段的范围
        if($fifMin>$start-450&&$start-450>$zeroMin){
            $start_date=$fifMin>$start-449 ? $fifMin : $zeroMin;
        }
        if($thirtyMin>$start-450&&$start-450>$fifMin){
            $start_date=$thirtyMin>$start-449 ? $thirtyMin : $fifMin;
        }
        if($f_fiveMin>$start-450&&$start-450>$thirtyMin){
            $start_date=$f_fiveMin>$start-449 ? $f_fiveMin : $thirtyMin;
        }
        if($start-450<$zeroMin){
            $start_date=$zeroMin;
        }
        if($start-450>$f_fiveMin){
            $start_date=$f_fiveMin;
        }
        $billTime=date('Y-m-d H:i:s',$start_date);//下单时间
        //下单时间》配送开始时间
        if($billTime>($tdate.' '.$startTime)){
            returnJsonData("哎呀,<br/>配送时间早于当前时间，<br/>您可以重新选择时间",400);
        }

        //下单时间+25分钟-7分钟 取最近的0 - 15 - 30 - 45 - 0 end

        //查询用户微信openID 昵称 头像
        $wxSql="select wx_openID,wx_nickname,wx_headimgurl from dunch_cust_master where pcustID=?";
        $wxInfo=$G_SHOP->DBCA->stmt_query($wxSql,'i',$G_SHOP->currentPCustID);

        //订单信息数组
        $bill = array(
            'custID'=>$G_SHOP->currentCustomerID,//会员手机号
            'country'=>440,//区ID
            'deliver_name'=>$username,//收货人手机号
            'deliver_address'=>$address,//收货地址
            'deliver_mobile'=>$tel,//收货人手机号
            'payTypeID'=>$payID,//支付方式ID
            'payment_method_id'=>0,//付款方式
            'send_date'=> $tdate,//收货日期
            'send_start_time' => $startTime,//配送开始时间
            'send_end_time' => $endTime,//配送结束时间
            'teamark' => $teamark,//请客理由
            'wxopenid' => $wxInfo[0]->wx_openID,//请客人用户opendID
            'wxnickname' =>  $wxInfo[0]->wx_nickname,//请客人微信昵称
            'wxheadimgurl' => $wxInfo[0]->wx_headimgurl//请客人微信头像
        );
        $pcustID=$G_SHOP->currentPCustID;
        $dunch=new dunch();
        $zt=$dunch->create_treat_bill($bill);
        if($zt['code']==200){
            $backArry=array(
                'bill_no'=>$zt['bill_no'],
                'ip'=>get_ip(),
                'pcustID'=>$pcustID,
            );
            returnJsonData($backArry,200);
        }else{
            returnJsonData($zt['message'],400);
        }



    }
    //获取配送时间
    public  function sendDate(){

        /********************************配送时间 start******************************/

        $date=date('Y-m-d',time());
        $dateTime=date('Y-m-d H:i:s',time());
        $weekarray=array("7","1","2","3","4","5","6");

        $tt=$weekarray[date("w",strtotime($date))];
        $start_time=strtotime(date('Y-m-d').'09:00:00');     //每天9点的时间戳
        $end_time=strtotime(date('Y-m-d').'17:15:00');       //每天17点的时间戳
        if(time()>strtotime(date('Y-m-d').'16:00:00')){
            if($tt==5){
                $x=3;
            }elseif($tt==6){
                $x=2;
            }else{
                $x=1;
            }
            $start_time=$start_time+86400*$x;
            $end_time=$end_time+86400*$x;
            $start=$start_time;

        }else{
            if($tt==6||$tt==7){
                if($tt==6){
                    $x=2;
                }
                elseif($tt==7){
                    $x=1;
                }
                $start_time=$start_time+86400*$x;
                $end_time=$end_time+86400*$x;
                $start=$start_time;
            }else{
                if(time()>$start_time){                           //判断是否在9~17点之间
                    $start= time()+1500;
                }else{
                    $start= $start_time-time()<=1500 ?  time()+1500 : $start_time;
                }
            }
        }

        $zeroMin=strtotime(date('Y-m-d H',$start).'00');  //当前小时内四个时间段 00  15  30  45
        $fifMin=strtotime(date('Y-m-d H',$start).'15');
        $thirtyMin=strtotime(date('Y-m-d H',$start).'30');
        $f_fiveMin=strtotime(date('Y-m-d H',$start).'45');
        //判断开始时间在四个时间段的范围
        if($fifMin>$start-450&&$start-450>$zeroMin){
            $start_date=$fifMin>$start-449 ? $fifMin : $zeroMin;
        }
        if($thirtyMin>$start-450&&$start-450>$fifMin){
            $start_date=$thirtyMin>$start-449 ? $thirtyMin : $fifMin;
        }
        if($f_fiveMin>$start-450&&$start-450>$thirtyMin){
            $start_date=$f_fiveMin>$start-449 ? $f_fiveMin : $thirtyMin;
        }
        if($start-450<$zeroMin){
            $start_date=$zeroMin;
        }
        if($start-450>$f_fiveMin){
            $start_date=$f_fiveMin;
        }
        $num=intval(($end_time-$start_date)/900);           //计算开始时间距离17:00有多少个时间段
        $last_time=($start_date+2700)+$num*900;
        if($last_time>$end_time){
            $num=$num-ceil(($last_time-$end_time)/900);
        }
//        <li><!--{$dateTime['start']}-->~<!--{$dateTime['end']}--></li>
        $sendHtml='';
        //循环输出时间段，组装数组,为null配送时间在五点之后
        for ($i=0; $i <= $num ; $i++) {
            $array_dateTime[]=array(
                'start'=>date('H:i',$start_date+$i*900),
                'end'=>date('H:i',($start_date+2700)+$i*900)
            );
            $sendHtml.="<li>".date('H:i',$start_date+$i*900).'~'.date('H:i',($start_date+2700)+$i*900)."</li>";
//            $array_dateTime[]=date('H:i',$start_date+$i*900).'~'.date('H:i',($start_date+2700)+$i*900);
        }
         $ulli='';
        if($array_dateTime[0]['end']<"12:00"){
            $ulli.="<li>上午";
            $ulli.="<ul>";
            foreach($array_dateTime as $array_dateTime_2){

                if($array_dateTime_2['end']<"12:00" && $array_dateTime_2['start']!=0){
                    $ulli.="<li>".$array_dateTime_2['start'].'~'.$array_dateTime_2['end']."</li>";

                }
            }
            $ulli.="</ul>";
            $ulli.="</li>";
        }
        $ulli.="<li>下午";
        $ulli.="<ul>";
        foreach($array_dateTime as $array_dateTime_2){
            if($array_dateTime_2['end']>"11:59"){
                $ulli.="<li>".$array_dateTime_2['start'].'~'.$array_dateTime_2['end']."</li>";
            }
        }
        $ulli.="</ul>";
        $ulli.="</li>";

        returnJsonData($ulli,200);

        /********************************配送时间 end******************************/
    }
    //被请人领取验证
    public function addDunchReceive(){

        global $G_SHOP;
        $drawNickname=$_COOKIE['bwxnickname'];
        $drawHeadimgurl=$_COOKIE['bwxheadimgurl'];
        $drawOpenid=$_COOKIE['bwxopenid'];

        $drawPhone='';

        if($G_SHOP->currentCustomerID){
            $drawPhone=$G_SHOP->currentCustomerID;
            //自己领
            if(!empty($_COOKIE['wxopenid'])){
                $drawOpenid=$_COOKIE['wxopenid'];
                $drawNickname=$_COOKIE['wxnickname'];
                $drawHeadimgurl=$_COOKIE['wxheadimgurl'];
            }

        }elseif($_COOKIE['dunchCookie_select']){
            $drawPhone=$_COOKIE['dunchCookie_select'];
        }else{
            returnJsonData('未验证手机号', 500);
        }
        if(empty($drawOpenid)){

            returnJsonData('未获取用户信息', 505);
        }

        $package_id=empty($_REQUEST['package_id'])?'':intval($_REQUEST['package_id']);      //获取参数套餐ID
        $bill_no=$_REQUEST['bill_no'];           //获取订单号'201504080000007185'
        $treatReason= $_REQUEST['treatReason'];  //获取参数请客理由

        if(empty($package_id)){
            returnJsonData('参数获取失败', 400);
        }
        if(empty($bill_no)){
            returnJsonData('参数获取失败', 400);
        }
        if(empty($treatReason))
            returnJsonData('参数获取失败', 400);


        $selSql="select a.bill_status,a.bill_code,a.deliver_cityid,a.deliver_city,a.billType,a.send_date,a.send_start_time,a.send_end_time,a.distribution_id,a.distribution_name,a.is_urgent,a.bill_no,b.billMark,a.custID from bill_master as a join dunch_treat  as b on a.bill_no= b.bill_no where a.bill_no=?";
        $selResult=$G_SHOP->DBCA->stmt_query($selSql,'s',$bill_no);

        if(empty($selResult))
            returnJsonData('该订单号不存在', 400);

        $treatSql="SELECT * FROM  dunch_treat where  bill_no=?";
        $treatInfo=$G_SHOP->DBCA->stmt_query($treatSql,'s',$bill_no);

        //判断是否已全部领取
        $checkSql="select count(1) as drawNum from dunch_draw  where drawBill_no=?";
        $dunchDrawResult=$G_SHOP->DBCA->stmt_query($checkSql,'s',$bill_no);
        foreach($dunchDrawResult as $key){
            $dunchNum=array(
                'bill_totalAmount'=>$treatInfo[0]->packageNumber,
                'drawNum'=>!empty($key->drawNum)?$key->drawNum:0,
            );
        }
        //核对订单商品总数量是否超过或等于已领取的不让领取
        if($dunchNum['bill_totalAmount']<=$dunchNum['drawNum'])

            returnJsonData('套餐数量已全部领取', 400);

        //判断该用户领取的时刻订单是否已生产，已生产不能领取
        if($selResult[0]->billMark==1)
            returnJsonData('套餐已生产，不能领取', 400);

        //判断该用户是否已领取
        $checkUserSql="select count(*) as countNum from dunch_draw where drawBill_no=? and drawOpenid=?";
        $DrawResult=$G_SHOP->DBCA->stmt_query($checkUserSql,'ss',$bill_no,$drawOpenid);
        if($DrawResult[0]->countNum>0)
            returnJsonData('您已领取，不能重复领取', 400);



         /*
         * 更改套餐库存start
         */
                //查询套餐销售日期
                $dateSql="select send_date from bill_master where bill_no=?";
                $dateInfo=$G_SHOP->DBCA->stmt_query($dateSql,'s',$bill_no);

                $updPackageSql="UPDATE dunch_sale  SET package_num=package_num-1 WHERE package_id=? and sale_date=? and package_num>=1";
                $cl=$G_SHOP->DBCA->stmt_query($updPackageSql,'is',$package_id,$dateInfo[0]->send_date);
                if(!$cl){
                    returnJsonData('库存不足', 400);
                }

        /*
         * 更改套餐库存end
         */
        /*
        * 更新订单主表信息start
        */
        //查询订单商品明细
        $strSql="select goods_name_str,bill_money from bill_master where bill_no=?";
        $strInfo=$G_SHOP->DBCA->stmt_query($strSql,'s',$bill_no);
        $packageSql="SELECT goodsName FROM  dunch_package_detail AS a JOIN goods_sale AS b ON a.product_code=b.product_code where a.package_id=? ";
        $packageInfo=$G_SHOP->DBCA->stmt_query($packageSql,'s',$package_id);
        if(empty($strInfo[0]->goods_name_str)){
            $newStr=$packageInfo[0]->goodsName.','.$packageInfo[1]->goodsName;
        }else{
            $newStr=$strInfo[0]->goods_name_str.','.$packageInfo[0]->goodsName.','.$packageInfo[1]->goodsName;
        }

        //计算商品价格  下午茶订单详情优化 add by junhui.li 2015-06-10 start
        try{
            $bill_bill_money_price=intval($strInfo[0]->bill_money); //订单金额
            $treat_package_number=intval($treatInfo[0]->packageNumber);  //订单总数量
            $bill_goods_price_avg=intval($bill_bill_money_price/$treat_package_number);  //得到平均数(整数)
            $first_bill_price= $bill_bill_money_price-$bill_goods_price_avg*($treat_package_number-1); //第一个领取商品价格

            $bill_count_price="select count(*) as countNum from dunch_draw where drawBill_no=?";
            $bill_count_price_result=$G_SHOP->DBCA->stmt_query($bill_count_price,'s',$bill_no);
            if($bill_count_price_result[0]->countNum>0){
                $goods_purchasePrice=$bill_goods_price_avg;
            }else{
                $goods_purchasePrice=$first_bill_price;
            }

        }catch (Exception $ex){

            error_log($ex->getMessage());
        }
        //计算商品价格  下午茶订单详情优化 add by junhui.li 2015-06-10 end
        $bill=new entity("bill_master");
        $bill->bill_no=$bill_no;
        $G_SHOP->DBCA->fetch($bill);
        $bill->goods_name_str=$newStr;
        $G_SHOP->DBCA->save($bill);

        /*
         * 更新订单主表信息end
         */
        try {

            $G_SHOP->DBCA->beginTransaction();  //开启事物
            //保存到用户领取记录表dunch_draw
            $dunch_draw = new entity('dunch_draw');
            $dunch_draw->createTime=date('Y-m-d H:i:s',time());
            $dunch_draw->createor='system';
            $dunch_draw->timeStamp=date('Y-m-d H:i:s',time());
            $dunch_draw->drawPhone=$drawPhone;
            $dunch_draw->drawOpenid=$drawOpenid;
            $dunch_draw->drawNickname=$drawNickname;
            $dunch_draw->drawHeadimgurl=$drawHeadimgurl;
            $dunch_draw->drawTime=date('Y-m-d H:i:s',time());
            $dunch_draw->drawLeaveWord=$treatReason;
            $dunch_draw->drawBill_no=$bill_no;
            $dunch_draw->package_id=$package_id;
            $G_SHOP->DBCA->save($dunch_draw);
            //通过package_id查询商品信息
            $goodInfoSql="select * from dunch_package_detail where package_id=?";
            $goodsInfo=$G_SHOP->DBCA->stmt_query($goodInfoSql,'i',$package_id);

            quanli_require('module/base/goods/quanliGoods.class.php');
            $quanliGoods = new quanliGoods( $G_SHOP->DBCA );

            $goods_id_str='';
            $goods_name_str='';
            foreach($goodsInfo as &$value){
                $args_array = array(
                    'product_code' => $value->product_code,
                );
                $goods_info = $quanliGoods->searchGoodsSaleDetail( $args_array );

                $sys_item_sql = 'SELECT * FROM sys_item WHERE itemCategoryID=36';
                $sys_item_data = &$G_SHOP->DBCA->stmt_query($sys_item_sql);

                //bill_goods订单商品表
                $bill_goods_obj = new entity('bill_goods');
                $bill_goods_obj->creator = 'system';
                $bill_goods_obj->bill_no = $bill_no;
                $bill_goods_obj->bill_goods_no = generate_seqno('seqno_bill_goods');
                $bill_goods_obj->goods_goodsID = $goods_info['goodsID'];
                $bill_goods_obj->goods_postID = $goods_info['postID'];
                $bill_goods_obj->product_code = $goods_info['product_code'];
                $bill_goods_obj->goods_name = $goods_info['goodsName'];
                $bill_goods_obj->goods_spec = $goods_info['spec'];
                $bill_goods_obj->goods_amount = 1;
                $bill_goods_obj->goods_marketPrice = $goods_info['marketPrice'];
                $bill_goods_obj->goods_storePrice = $goods_info['salePrice'];
                //计算商品价格  下午茶订单详情优化 add by junhui.li 2015-06-10 start
                //$bill_goods_obj->goods_purchasePrice = $goods_info['salePrice'];
                $bill_goods_obj->goods_purchasePrice = strstr($sys_item_data[0]->itemName,$goods_info['product_code'])?0:$goods_purchasePrice;
                //计算商品价格  下午茶订单详情优化 add by junhui.li 2015-06-10 end
                $bill_goods_obj->goods_pointsPrice = 0;
                $bill_goods_obj->goods_points = 0;
                $bill_goods_obj->goods_weight = 0;
                $bill_goods_obj->goods_from = 1;
                $bill_goods_obj->goods_groupID = 0;
                $bill_goods_obj->segmentation = 0;
                $goods_id_str.=$goods_info['postID'].',';
                $goods_name_str.=$goods_info['goodsName'].',';
                $bill_goods_array[] = $bill_goods_obj;


            }

            foreach($bill_goods_array as &$goods_obj) {
                //如果订单状态为已审核 保存订单商品生产表
                if ($selResult[0]->bill_status>0) {
                    $bill_goods_product = new entity('bill_goods_product');
                    $bill_goods_product->timeStamp = $G_SHOP->sys_datetime;
                    $bill_goods_product->creator = 'system';
                    $bill_goods_product->createTime = $G_SHOP->sys_datetime;
                    $bill_goods_product->bill_no = $goods_obj->bill_no;
                    $bill_goods_product->bill_goods_no = $goods_obj->bill_goods_no;
                    $bill_goods_product->bill_code = $selResult[0]->bill_code;
                    $bill_goods_product->cityID = $selResult[0]->deliver_cityid;
                    $bill_goods_product->cityName = $selResult[0]->deliver_city;
                    $bill_goods_product->billType = $selResult[0]->billType;
                    $bill_goods_product->send_date = $selResult[0]->send_date;
                    $bill_goods_product->send_start_time = $selResult[0]->send_start_time;
                    $bill_goods_product->send_end_time = $selResult[0]->send_end_time;
                    $bill_goods_product->distribution_id = $selResult[0]->distribution_id;
                    $bill_goods_product->distribution_name = $selResult[0]->distribution_name;
                    $bill_goods_product->is_urgent = $selResult[0]->is_urgent;
                    $bill_goods_product->goods_postID = $goods_obj->goods_postID;
                    $bill_goods_product->product_code = $goods_obj->product_code;
                    $bill_goods_product->goods_name = $goods_obj->goods_name;
                    $bill_goods_product->goods_spec = $goods_obj->goods_spec;
                    $bill_goods_product->goods_amount = $goods_obj->goods_amount;
                    $bill_goods_product->tableware_amount = $goods_obj->tableware_amount;
                    $bill_goods_product->extra_tableware_amount = $goods_obj->extra_tableware_amount;
                    $bill_goods_product->candle_amount = $goods_obj->candle_amount;
                    $bill_goods_product->extra_candle_amount = $goods_obj->extra_candle_amount;
                    $bill_goods_product->birthday_card = $goods_obj->birthday_card;
                    $bill_goods_product->segmentation = $goods_obj->segmentation;
                    $bill_goods_product->goods_remark = $goods_obj->goods_remark;

                    $G_SHOP->DBCA->save($bill_goods_product);

                }
                //保存bill_goods订单商品表里
                $G_SHOP->DBCA->save($goods_obj);

            }


//
//            $detailSql="select goods_sale.* from  dunch_package_detail join goods_sale on dunch_package_detail.product_code=goods_sale.product_code  where package_id=?";
//            $detailQuest=$G_SHOP->DBCA->stmt_query($detailSql,'s',$package_id);
//            $logSql="select stock_id from  dunch_stock  where  product_code=?";
//            $logQuest=$G_SHOP->DBCA->stmt_query($logSql,'s',$detailQuery->product_code);
//
//            $dunch_stock_log=new entity("dunch_stock_log");
//            $dunch_stock_log->stock_id=$logQuest[0]->stock_id;
//
//            $dunch_stock_log->log_type=3;
//            $dunch_stock_log->amount=$bill_goods_2[0]['num'];
//            $G_SHOP->DBCA->save($dunch_stock_log);
//            $postID.=$detailQuery->postID.",";
//            $goodsName.=$detailQuery->goodsName."+";
//            $stock_id=$logQuest[0]->stock_id;





            //查询下午茶订单明细表,如果有符合条件的记录 购买数量(buy_amount)加1,否则创建该记录
            $dunch_bill_detail_sql='select buy_amount,count(*) as countNum from dunch_bill_detail where  bill_no=? and package_id=?';
            $dunch_bill_detail_result=$G_SHOP->DBCA->stmt_query($dunch_bill_detail_sql,'si',$bill_no,$package_id);

            if($dunch_bill_detail_result[0]->countNum>0){
                //更新符合条件的buy_amount购买数量+1
                $bill_detail_sql="update dunch_bill_detail set buy_amount =buy_amount+1 where bill_no=? and package_id=?";
                $G_SHOP->DBCA->stmt_query($bill_detail_sql,'si',$bill_no,$package_id);

            }else{
                //不符合条件的创建该记录在订单明细表
                $dunch_package_sql='select a.package_name,b.sale_id from dunch_package as a join dunch_sale as b on a.package_id=b.package_id where a.package_id=?';
                $dunch_package_result=$G_SHOP->DBCA->stmt_query($dunch_package_sql,'i',$package_id);

                $dunch_bill_detail = new entity('dunch_bill_detail');
                $dunch_bill_detail->timeStamp=$G_SHOP->sys_datetime;
                $dunch_bill_detail->creator='system';
                $dunch_bill_detail->createTime=$G_SHOP->sys_datetime;
                $dunch_bill_detail->bill_no=$bill_no;
                $dunch_bill_detail->bill_code=$selResult[0]->bill_code;
                $dunch_bill_detail->package_id=$package_id;
                $dunch_bill_detail->package_name=$dunch_package_result[0]->package_name;
                $dunch_bill_detail->goods_id_str=rtrim($goods_id_str, ',');
                $dunch_bill_detail->goods_name_str=rtrim($goods_name_str, ',');
                $dunch_bill_detail->buy_amount=1;
                //$dunch_bill_detail->stock_id=$dunch_package_result[0]->sale_id;
                $G_SHOP->DBCA->save($dunch_bill_detail);
            }

            /*****领取完成  请客订单领取完成的告知 start********/
            $dunchTreatSql="SELECT packageNumber FROM dunch_treat WHERE bill_no=?";
            $dunchTreatInfo=$G_SHOP->DBCA->stmt_query($dunchTreatSql,'s',$bill_no);
            $dunchDrawSql="SELECT count(1) as gonum FROM dunch_draw WHERE drawBill_no=?";
            $dunchDrawInfo=$G_SHOP->DBCA->stmt_query($dunchDrawSql,'s',$bill_no);

            if($dunchTreatInfo[0]->packageNumber==$dunchDrawInfo[0]->gonum){

                $updateSql="update dunch_treat set billMark=1 where bill_no=?";
                $G_SHOP->DBCA->stmt_query($updateSql, 's', $bill_no);
                //实例化短信类
                $quanliSms = new quanliSms();
                $smsInfo=array(
                    '$bill_code'=>$selResult[0]->bill_code,//订单编号

                    '$send_time'=>$selResult[0]->send_start_time."-".$selResult[0]->send_end_time,//配送时间
                );
                $sms_content = $quanliSms->getSmsContent( 'dunch_treat_all',$smsInfo);
                if (!$sms_content) {
                    returnJsonData('短信初始化失败', 404);
                }
                //发送短信
                $semd=$quanliSms->sendSMS( $selResult[0]->custID, $sms_content );

            }


            /*****领取完成  请客订单领取完成的告知 end  t********/

            $G_SHOP->DBCA->commit();
            returnJsonData('ok', 200);

        } catch (Exception $e) {

            $G_SHOP->DBCA->rollBack();
            if ($e->getCode() > 0) {
                return array('code' => $e->getCode(),'message' => $e->getMessage());
            } else {
                error_log($e->getMessage());
                returnJsonData('系统错误', 500);
            }

        }


    }
    //选择套餐时验证套餐库存
    public function checkSelect(){
        global $G_SHOP;
        $user='';
        if($G_SHOP->currentCustomerID){
            $user=$G_SHOP->currentCustomerID;
        }elseif($_COOKIE['dunchCookie_select']){
            $user=$_COOKIE['dunchCookie_select'];
        }
        if($user==''|| empty($user)){
            returnJsonData('未验证手机', 400);
        }else{
            returnJsonData('已验证手机', 200);
        }

    }
    //申请权益
    public function treatApply(){
        global $G_SHOP;
        $_REQUEST['username'];//用户名
        $_REQUEST['usertel'];//手机号
        $_REQUEST['areaID'];//区ID
        $_REQUEST['address'];//详细地址
        //查询该手机是否为下午茶会员
        $treatSql="select count(1) as dunchNum from  dunch_cust_master where  custID=?";
        $treatInfo=$G_SHOP->DBCA->stmt_query($treatSql,'s',$_REQUEST['usertel']);
        $dunch_tucao=new entity("dunch_tucao");
        $dunch_tucao->custName=$_REQUEST['username'];
        $dunch_tucao->mobile=$_REQUEST['usertel'];
        $dunch_tucao->areaID=$_REQUEST['areaID'];
        $dunch_tucao->content=$_REQUEST['address'];
        $dunch_tucao->platform=1;
        if($treatInfo[0]->dunchNum){
            $dunch_tucao->apply=1;
        }
        $G_SHOP->DBCA->save($dunch_tucao);
        if($treatInfo[0]->dunchNum){
            returnJsonData('已收到您的请客心愿！若您的坐标在下午茶配送范围，权限开通后，会有短信飞到手中~', 200);
        }else{
            returnJsonData('已收到您的购买心愿！若您的坐标在下午茶配送范围，权限开通后，会有短信飞到手中~', 200);
        }


    }

    /**
     * 摇奖
     */

    public function ernie(){
        global $G_SHOP;
        $buyNum=$_REQUEST['buyNum'];//请客人数
        $tdate=$_REQUEST['tdate'];//套餐销售日期

        if(isset($buyNum)&&!empty($buyNum) && $buyNum>1 && $buyNum <11){


                //取四个随机数
                $numa=rand(0,$buyNum);
                $numb=rand(0,$buyNum);
                $numc=rand(0,$buyNum);
              //  $numd=rand(0,$buyNum);
                $num3=1;//默认免单1
                //普通的概率
//                if(($numd-$numc-$numb-$numa) > 0 || ($numd-$numc-$numb-$numa) == 0){
//                    $num3=($numd-$numc-$numb-$numa);
//                }
                //购买数量为2时，取0-10之间的随机数，如数值为1则免单1 否则免单0
                if($buyNum==2){
                    $num_2=rand(0,10);
                    if($num_2==1){
                        $num3=1;
                    }else{
                        $num3=0;
                    }
                }else{
                    $cnum=($numc-$numb-$numa) < 0 ? 0:($numc-$numb-$numa) ;
                    $num3=ceil($cnum/3);
                }
//                //购买数量为3，若（第四个随机数小于前三个随机数之和）则免单为0
//                if( $buyNum==3){
//                    if($numd<($numc+$numb+$numa)){
//                        $num3=0;
//                    }else{
//                        $num3=1;
//                    }
//                }
//                //购买数量大于3，若（第四个随机数小于前三个随机数之和）则免单为1
//                if($buyNum>3){
//                    if($numd<($numc+$numb+$numa)){
//                        $num3=1;
//                    }
//                }


                $numIfo=array(
                    'mnum'=>$num3,
                    'buyNum'=>$buyNum,
                    'tdate'=>$tdate
                );
        }else{
            $numIfo=array(
                'mnum'=>0,
                'buyNum'=>2,
                'tdate'=>$tdate
            );
        }


        $G_SHOP->sessionCache_set("numIfo",$numIfo,G_LOGINSESSION_TIMEOUT);

        returnJsonData($numIfo, 200);
    }





}
